/* eslint-disable @typescript-eslint/brace-style */

import { api } from "../api";

// 获取公钥
export const getPublicKey = async () => {
  try {
    const response = await api.get("/java/user/publicKey");
    return response.data;
  } catch (error) {
    throw new Error("获取公钥失败");
  }
};

// 登录请求
export const loginUser = async (
  username: string,
  encryptedPassword: string | false,
) => {
  // 判断加密密码是否正确
  if (!encryptedPassword)
    throw new Error("加密密码错误");

  try {
    const response = await api.post("/java/user/login", {
      username,
      password: encryptedPassword,
    });
    return response.data;
  } catch (error) {
    throw new Error("登录请求失败");
  }
};

// 刷新 Token
export const refreshToken = async () => {
  try {
    const response = await api.post("/java/user/refresh");
    return response.data;
  } catch (error) {
    throw new Error("刷新 Token 失败");
  }
};

// 学校登录请求
export const schoolLoginUser = async (
  username: string,
  encryptedPassword: string | false,
) => {
  // 判断加密密码是否正确
  if (!encryptedPassword)
    throw new Error("加密密码错误");
  try {
    const response = await api.post("/java/user/school_login", {
      username,
      password: encryptedPassword,
    });
    return response.data;
  } catch (error) {
    throw new Error("学校登录请求失败");
  }
};

export const getUserInfo = async () => {
  try {
    const response = await api.get('/java/user/whoami_frontend')
    return response.data;
  } catch (error) {
    throw new Error("获取用户信息失败");
  }
}

// 判断用户是否是教师
export const allowedUserTypes = ['BIAdmin', 'L0101', 'L0107', 'L0108', 'L0109']
export const isTeacher = async () => {
  try {
    const response = await getUserInfo();
    const userType = response.userType;
    if (userType && allowedUserTypes.includes(userType))
      return true;
    else
      return false;
  } catch (error) {
    throw new Error("判断教师身份失败");
  }
}

// 学校CAS协议登录
export const schoolCASLoginUser = async (ticket: string, route = '/login') => {
  try {
    const response = await api.post("/java/user/school_cas_login", {
      ticket,
      route,
    });
    return response.data;
  }
  catch (error) {
    console.error(error);
    throw new Error(`学校CAS登录请求失败${error}`);
  }
}
